#!/bin/bash

set -e

# Source debconf library.
. /usr/share/debconf/confmodule

# defaults file
CONFIG="/etc/default/@PACKAGE@"

# get number of cores so we can set number of GC threads
CPU_CORES=$(cat /proc/cpuinfo | grep processor | wc -l)
NEW_RATIO=8

# defaults for JVM
HEAP_SIZE="512"

purge_line () {
    if [ -s "$1" ]; then
        # safely create a temp file
        t=$(tempfile) || exit
        trap "rm -f -- '$t'" EXIT

        # purge line
        sed "/$2/d" "$1" > "$t"
        mv "$t" "$1"

        # cleanup temp file
        rm -f -- "$t"
        trap - EXIT
    fi
}

sed_file () {
    # safely create a temp file
    t=$(tempfile) || exit
    trap "rm -f -- '$t'" EXIT

    sed "s/$1/$2/g" "$3" > "$t"
    mv "$t" "$3"

    # cleanup temp file
    rm -f -- "$t"
    trap - EXIT
}

case "$1" in
    configure)

        ##### deal with logs #####
        mkdir -p /var/log/@PACKAGE@
        chown jmxtrans:jmxtrans /var/log/@PACKAGE@

        if [ ! -d /usr/share/@PACKAGE@/logs -a ! -h /usr/share/@PACKAGE@/logs ]; then
            cd /usr/share/@PACKAGE@
            ln -fs /var/log/@PACKAGE@ logs
        fi
        ##### deal with logs #####

        # collect user inputs
        db_get @PACKAGE@/jvm_heap_size
        if [ ! -z "$RET" ]; then
            HEAP_SIZE="${RET}"
        fi

        HEAP_NUMBER=$(echo $HEAP_SIZE|sed 's/[a-zA-Z]//g')
        NEW_SIZE=$(expr $HEAP_SIZE / $NEW_RATIO)

        mkdir -p /var/lib/@PACKAGE@ || true
        chown jmxtrans:jmxtrans /var/lib/@PACKAGE@

        # populate defaults file
        if [ ! -e "$CONFIG" ]; then
            echo "# default file for package @PACKAGE@" > "$CONFIG"
            echo "export LOG_DIR=\"/var/log/@PACKAGE@\"" >> "$CONFIG"
            echo "export SECONDS_BETWEEN_RUNS=60" >> "$CONFIG"
            echo "export JSON_DIR=\"/var/lib/@PACKAGE@\"" >> "$CONFIG"
            echo "export HEAP_SIZE=${HEAP_SIZE}" >> "$CONFIG"
            echo "export NEW_SIZE=${NEW_SIZE}" >> "$CONFIG"
            echo "export CPU_CORES=${CPU_CORES}" >> "$CONFIG"
            echo "export NEW_RATIO=${NEW_RATIO}" >> "$CONFIG"
            echo "export LOG_LEVEL=debug" >> "$CONFIG"
        fi

        chmod 644 "${CONFIG}" || true
    ;;
    *)
        echo "postinst called with unknown argument \`$1'" >&2
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0

